import tkinter as tk
import json
from tkinter import font
import card_list
from card import show_card_ledger
from select import select_cards
from random import choice

# 定义全局函数，以便在 create_ui 函数中使用
def load_cards():
    with open('card.json', 'r', encoding='utf-8') as file:
        return json.load(file)['cards']

# 定义全局变量
card_fragments = {}
current_task = None
goal = 0
global confirm_frame, task_frame, task_labels

# 函数：加载并更新当前任务和目标
def load_and_update_task_and_goal():
    global current_task, goal
    try:
        with open('wait.json', 'r', encoding='utf-8') as file:
            current_task = json.load(file)['task']
    except FileNotFoundError:
        current_task = None
    
    try:
        with open('goal.json', 'r', encoding='utf-8') as file:
            goal_data = json.load(file)
            goal = goal_data.get('goal', 0)
    except FileNotFoundError:
        goal = 0

    update_task_display(root)

# 函数：更新任务显示
def update_task_display(root):
    global task_label
    if current_task:
        task_label.config(text=f"当前任务：{current_task['content']}")
    else:
        task_label.config(text="当前任务：空")

# 完成按钮的事件处理
def complete_task():
    global goal
    if current_task:
        # 更新目标值
        goal += current_task['goal']
        with open('goal.json', 'w', encoding='utf-8') as file:
            json.dump({'goal': goal}, file, ensure_ascii=False, indent=4)
    reset_wait_json()

# 放弃按钮的事件处理
def abandon_task():
    reset_wait_json(root)

# 重置wait.json
def reset_wait_json():
    global current_task
    # 重置当前任务
    current_task = None
    with open('wait.json', 'w', encoding='utf-8') as file:
        json.dump({"task": {}}, file, ensure_ascii=False, indent=4)
    # 更新任务显示
    update_task_display(root)

# 任务抽取相关函数
def show_tasks(root):
    global task_frame, task_labels  # 声明全局变量 task_frame 和 task_labels
    task_labels = []  # 初始化任务标签列表
    def load_tasks():
        try:
            with open('task.json', 'r', encoding='utf-8') as file:
                return json.load(file)['tasks']
        except FileNotFoundError:
            print("未找到 task.json 文件")
            return []

    tasks = load_tasks()

    # 读取任务数据
    tasks = load_tasks()
    task1 = choice(tasks)
    tasks = [task for task in tasks if task['id'] != task1['id']]
    task2 = choice(tasks)
    tasks = [task for task in tasks if task['id'] != task2['id']]
    task3 = choice(tasks)

    # 保存任务到 this.json
    data = {'task1': task1, 'task2': task2, 'task3': task3}
    with open('this.json', 'w', encoding='utf-8') as file:
        json.dump(data, file, ensure_ascii=False, indent=4)

    # 创建任务显示区域
    task_frame = tk.Frame(root, bg='white')
    task_frame.pack(side=tk.TOP, pady=20, fill=tk.X)

    # 创建并存储任务标签引用
    for task, index in zip([task1, task2, task3], range(1, 4)):
        task_label = tk.Label(task_frame, text=f"任务 {index}: {task['content']}",
                              font=('Helvetica', 12), bg='white', fg='black')
        task_label.pack(side=tk.TOP, pady=5, anchor='center')  # 使用 top 方式打包，并设置锚点为中间
        task_labels.append(task_label)  # 将标签添加到列表中
        # 任务标签绑定点击事件
        task_label.bind("<Button-1>", lambda event, task=task: task_selected(task,root))

# 任务选择确认界面
def task_selected(task, root):
    confirm_frame = tk.Frame(root, bg='white')
    confirm_frame.pack(side=tk.TOP, pady=10, fill=tk.BOTH, expand=True)

    confirm_text = tk.Label(confirm_frame, text=f"是否要接受任务：{task['content']}?", font=('Helvetica', 12))
    confirm_text.pack(side=tk.TOP, pady=10, anchor='center')

    # 创建一个水平布局的按钮容器
    buttons_frame = tk.Frame(confirm_frame)
    buttons_frame.pack(side=tk.TOP, pady=10)

    # 确定按钮
    accept_button = tk.Button(buttons_frame, text="确定", command=lambda: accept_task_callback(task, root, confirm_frame))
    accept_button.pack(side=tk.LEFT, padx=10, expand=True)  # 设置 expand=True

    # 我再想想按钮
    decline_button = tk.Button(buttons_frame, text="我再想想", command=lambda: decline_task_callback(root, confirm_frame))
    decline_button.pack(side=tk.LEFT, padx=10, expand=True)  # 设置 expand=True

def accept_task_callback(task, root, confirm_frame):
    save_task_to_wait_json(task, root)

    # 隐藏询问框和所有任务标签
    confirm_frame.pack_forget()
    for label in task_labels:
        label.pack_forget()  # 隐藏任务标签
    # 隐藏任务显示区域
    task_frame.pack_forget()

    # 重新加载并更新任务和目标信息
    load_and_update_task_and_goal()

    # 更新UI
    update_task_display(root)

def decline_task_callback(root, confirm_frame):
    # 仅隐藏询问框
    confirm_frame.pack_forget()

def save_task_to_wait_json(task, root):
    with open('wait.json', 'w', encoding='utf-8') as file:
        json.dump({"task": task}, file, ensure_ascii=False, indent=4)

# 创建UI
def create_ui(root):
    global check_ledger_button, card_name_label, task_button, card_description_label, card_count_label, card_button

    # 设置窗口背景颜色
    root.configure(bg='white')

    # 设置按钮的字体大小
    button_font = tk.font.Font(size=20)

    # 设置查看图鉴的按钮
    check_ledger_button = tk.Button(root, text="查看图鉴", command=lambda: show_card_ledger(root), bg='white')
    check_ledger_button.pack(side=tk.TOP, pady=5)

    # 设置抽取任务的按钮
    task_button = tk.Button(root, text="抽取任务", command=lambda: show_tasks(root), bg='white')
    task_button.pack(side=tk.TOP, pady=5)

    # 设置抽卡的按钮
    card_button = tk.Button(root, text="去抽卡", command=lambda: select_cards(root), bg='white')
    card_button.pack(side=tk.TOP, pady=5)

    # 创建显示卡牌数量的标签
    card_count_label = tk.Label(root, text="卡牌总数: ", bg='white', fg='black')
    card_count_label.pack(side=tk.TOP, pady=5)

    card_count = len(load_cards())
    card_count_label.config(text=f"卡牌总数: {card_count}")

    # 创建显示当前任务的标签
    global task_label
    task_label = tk.Label(root, text="当前任务：", bg='white', fg='black')
    task_label.pack(side=tk.TOP, pady=20)  # 增加垂直间距

    # 创建完成按钮和放弃按钮的容器
    buttons_frame = tk.Frame(root)
    buttons_frame.pack(side=tk.TOP, pady=10)

    # 完成按钮
    complete_button = tk.Button(buttons_frame, text="完成", command=complete_task)
    complete_button.pack(side=tk.LEFT, padx=10)  # 使用 LEFT 并设置间距

    # 放弃按钮
    abandon_button = tk.Button(buttons_frame, text="放弃", command=abandon_task)
    abandon_button.pack(side=tk.LEFT, padx=10)  # 使用 LEFT 并设置间距


    # 调用函数加载任务和目标，并更新显示
    load_and_update_task_and_goal()

# 创建主窗口
root = tk.Tk()
root.title("抽卡游戏")

# 设置窗口大小
root.geometry("1600x1200")

# 创建UI
create_ui(root)

# 运行主循环
root.mainloop()